package main

import (
	"fmt"
	"net"
	"strconv"
	"strings"

	//"github.com/sirupsen/logrus"
	"github.com/hashicorp/consul/api"
)

func main() {
	var lastIndex uint64
	config := api.DefaultConfig()
	config.Address = "127.0.0.1:8100" //consul server

	client, err := api.NewClient(config)
	if err != nil {
		fmt.Println("api new client is failed, err:", err)
		return
	}

	HealthCritical, asci, err := client.Agent().AgentHealthServiceByName("CCGameServerFishZC")
	if err == nil {
		fmt.Println("__1")
		if strings.Compare(HealthCritical, api.HealthPassing) == 0 {
			for _, v := range asci {
				fmt.Println("___")
				if strings.Compare(v.AggregatedStatus, api.HealthPassing) == 0 {
					type MetaInfo struct {
						Sa   api.ServiceAddress
						Meta map[string]string
					}
					mi := MetaInfo{Sa: v.Service.TaggedAddresses["wan"], Meta: v.Service.Meta}
					if mi.Sa.Address != "" && mi.Sa.Port > 0 {
						fmt.Println(mi)
					}
				}
			}
		}
	}
	fmt.Println("err1 ", err, asci)

	services, metainfo, err := client.Health().Service("CCGameServerFishZC", "v1000", true, &api.QueryOptions{
		WaitIndex: lastIndex, // 同步点，这个调用将一直阻塞，直到有新的更新
	})
	if err != nil {
		//logrus.Warn("error retrieving instances from Consul: %v", err)
		fmt.Printf("err %v", err)
	}
	lastIndex = metainfo.LastIndex

	addrs := map[string]struct{}{}
	for _, service := range services {
		fmt.Println("service.Service.Address:", service.Service.Address, "service.Service.Port:", service.Service.Port)
		addrs[net.JoinHostPort(service.Service.Address, strconv.Itoa(service.Service.Port))] = struct{}{}
	}
}